<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>聊天中心</title>
</head>
<body>
    <div id="willhidden">Welcome<br/>姓名<input id="name" type="text"><button onclick="getname()">确认姓名</button></div>
    <div id="show" ><input id="name2" type="text"/><input id="text" type="text"/>
    <button onclick="send()">发送消息</button>
    <hr/>
    <button onclick="closeWebSocket()">关闭WebSocket连接</button>
    <hr/>
    </div>
    <div id="message"></div>
</body>

<script type="text/javascript">
document.getElementById("show").style.display="none";
var websocket = null;
var name="null";
function getname(){
	let namebox=document.getElementById("name");
	name=namebox.value;
	connect(name);
	document.getElementById("willhidden").style.display="none";
	document.getElementById("show").style.display="";
	
}
function connect(nikname){
   
    
    if ('WebSocket' in window) {
    	let url="ws://172.7.41.152:8088/blogserver/websocket/"+nikname;
        websocket = new WebSocket(url);
       
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

   
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };

  
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket连接成功");
    }

 
    websocket.onmessage = function (event) {
    	
        setMessageInnerHTML(event.data);
    }

   
    websocket.onclose = function () {
        setMessageInnerHTML("WebSocket连接关闭");
    }

    
    window.onbeforeunload = function () {
        closeWebSocket();
    }
    
}
   
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    
    function closeWebSocket() {
        websocket.close();
    }

    
    function send() {
        var message = document.getElementById('text').value;
        var op = document.getElementById('name2').value;
        if(op==""){
        	op="all";
        }
       
       var map={};
       map['op']=op;
       map['message']=message;
       map['ob']=name
       jsonstr=JSON.stringify(map);
        websocket.send(jsonstr);
    }
</script>
</html>